package client

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/config"
	"likeadmin/core/request"
	"likeadmin/core/response"
	"likeadmin/model/client"
)

type IRechargeReportService interface {
	List(c *gin.Context, page request.PageReq, listReq req.RechargeReportListReq) (res response.PageResp, e error)
	Statistic(adminId uint, listReq req.RechargeReportListReq) (res map[string]any, e error)
}

// NewRechargeReportService 初始化
func NewRechargeReportService(db *gorm.DB) IRechargeReportService {
	return &rechargeReportService{db: db}
}

// rechargeReportService 外推充值统计服务实现类
type rechargeReportService struct {
	db *gorm.DB
}

// List 外推充值统计列表
func (srv rechargeReportService) List(c *gin.Context, page request.PageReq, listReq req.RechargeReportListReq) (res response.PageResp, e error) {
	// 分页信息
	limit := page.PageSize
	offset := page.PageSize * (page.PageNo - 1)
	// 查询
	model := srv.db.Model(&client.RechargeReport{})

	adminId := config.AdminConfig.GetAdminId(c)
	if adminId != 1 {
		model = model.Where("creater_id = ?", adminId)
	}

	if listReq.SourceId != "" {
		model = model.Where("source_id = ?", listReq.SourceId)
	}
	if listReq.AccountId != "" {
		model = model.Where("account_id = ?", listReq.AccountId)
	}

	if listReq.DateStartTime != "" {
		model = model.Where("date >= ?", listReq.DateStartTime)
	}

	if listReq.DateEndTime != "" {
		model = model.Where("date <= ?", listReq.DateEndTime)
	}

	model = model.Where("delete_time = ?", 0)
	// 总数
	var count int64
	err := model.Count(&count).Error
	if e = response.CheckErr(err, "List Count err"); e != nil {
		return
	}
	// 数据
	var objs []client.RechargeReport
	err = model.Limit(limit).Offset(offset).Order("date desc,create_time desc").Find(&objs).Error
	if e = response.CheckErr(err, "List Find err"); e != nil {
		return
	}

	accountIds := make([]string, len(objs))
	for i, obj := range objs {
		accountIds[i] = obj.AccountId
	}
	var accounts []client.Account
	if len(accountIds) > 0 {
		err = srv.db.Model(&client.Account{}).Where("account_id IN ?", accountIds).Find(&accounts).Error
		if e = response.CheckErrDBNotRecord(err, "account_id Find err"); e != nil {
			return
		}
	}
	accountMap := make(map[string]client.Account)
	for _, account := range accounts {
		accountMap[account.AccountId] = account
	}

	resps := []resp.RechargeReportResp{}
	response.Copy(&resps, objs)

	for i, v := range resps {
		resps[i].AccountTitle = accountMap[v.AccountId].AccountTitle
	}
	return response.PageResp{
		PageNo:   page.PageNo,
		PageSize: page.PageSize,
		Count:    count,
		Lists:    resps,
	}, nil
}
func (srv rechargeReportService) Statistic(adminId uint, listReq req.RechargeReportListReq) (res map[string]any, e error) {

	statistic := map[string]any{
		"cost":     0,
		"recharge": 0,
		"users":    0,
	}

	model := srv.db.Model(&client.RechargeReport{})

	if adminId != 1 {
		model.Where("creater_id = ?", adminId)
	}

	if listReq.AccountId != "" {
		model = model.Where("account_id = ?", listReq.AccountId)
	}

	if listReq.DateStartTime != "" {
		model = model.Where("date >= ?", listReq.DateStartTime)
	}

	if listReq.DateEndTime != "" {
		model = model.Where("date <= ?", listReq.DateEndTime)
	}

	model = model.Where("delete_time = ?", 0)

	// 成本
	var totalCost uint
	_ = model.Select("IFNULL(SUM(cost),0)").Scan(&totalCost).Error

	// 充值
	var totalRecharge uint
	_ = model.Select("IFNULL(SUM(recharge),0)").Scan(&totalRecharge).Error

	// 用户数
	var totalUsers uint
	_ = model.Select("IFNULL(SUM(users),0)").Scan(&totalUsers).Error

	// 转换为元并保留两位小数
	costFloat := float64(totalCost) / 100.0
	rechargeFloat := float64(totalRecharge) / 100.0

	statistic["cost"] = fmt.Sprintf("%.2f", costFloat)
	statistic["recharge"] = fmt.Sprintf("%.2f", rechargeFloat)
	statistic["users"] = totalUsers

	return statistic, e
}
